85. Maximal Rectangle - LeetCode Solution


Dynamic Programming Stack

Python Code:

class Solution:
    def maximalRectangle(self, matrix: List[List[str]]) -> int:
        def MHA(heights):
            if len(heights) == 0:
                return 0

            stack = []

            left = []
            right = []

            for i in range(len(heights)):

                while len(stack) != 0 and heights[stack[-1]] >= heights[i]:
                    stack.pop()

                if len(stack) == 0:
                    left.append(0)
                else:
                    left.append(stack[-1] + 1)

                stack.append(i)

            stack = []

            for i in range(len(heights) - 1, -1, -1):
                while len(stack) != 0 and heights[stack[-1]] >= heights[i]:
                    stack.pop()

                if len(stack) == 0:
                    right.append(len(heights) - 1)
                else:
                    right.append(stack[-1] - 1)

                stack.append(i)

            right = right[::-1]


            ans = []

            for i in range(len(right)):
                ans.append((right[i] - left[i] + 1) * heights[i])

            return max(ans)
        
        
        if len(matrix) == 0:
            return 0
        area = []


        x = [0] * len(matrix[0])


        for i in range(len(matrix)):

            for j in range(len(matrix[i])):
                if int(matrix[i][j]) == 0:
                    x[j] = 0
                else:
                    x[j] += int(matrix[i][j])


            area.append(MHA(x))


        print(max(area))
        return max(area)


Comments

Submit
0 Comments
More Questions

1478A - Nezzar and Colorful Balls
1581B - Diameter of Graph
404A - Valera and X
908A - New Year and Counting Cards
146A - Lucky Ticket
1594C - Make Them Equal
1676A - Lucky
1700B - Palindromic Numbers
702C - Cellular Network
1672C - Unequal Array
1706C - Qpwoeirut And The City
1697A - Parkway Walk
1505B - DMCA
478B - Random Teams
1705C - Mark and His Unfinished Essay
1401C - Mere Array
1613B - Absent Remainder
1536B - Prinzessin der Verurteilung
1699B - Almost Ternary Matrix
1545A - AquaMoon and Strange Sort
538B - Quasi Binary
424A - Squats
1703A - YES or YES
494A - Treasure
48B - Land Lot
835A - Key races
1622C - Set or Decrease
1682A - Palindromic Indices
903C - Boxes Packing
887A - Div 64